<template>
  <el-card style="height: 100%;box-sizing: border-box;">
    <el-row :gutter="10">
      <el-col :span="4">
        <el-image :src="BASE_URL + tableData.poster"
                  style="width: 180px;height: auto;"
                  alt="Film poster"/>
      </el-col>
      <el-col :span="9">
        <div style="margin-left: 20px;">
          <p style="font-size: 20px;font-weight: bold">{{ tableData.filmName }}</p>
          <p style="font-size: 14px;color: #666666"> ({{ tableData.englishName }})</p>
          <p>{{ tableData.directorName }}</p>
          <p>{{ tagFormatter(tableData, null, tableData.tag) }}</p>
          <p>{{ nationalityFormatter(tableData, null, tableData.region) }} / {{ tableData.duration }}分钟</p>
          <p>{{ tableData.releaseDate }} 上映 </p>
          <span>电影评分 : </span>
          <p style="font-size: 30px;color: #ebbe56;
          font-weight: bold;">{{ tableData.filmRating }}</p>
        </div>
      </el-col>
      <el-col :span="3">
        <p>操作设置</p>
        <el-button link type="primary" @click="editFilmInfo"
        >编辑信息
        </el-button>
        <br>
        <el-button link type="primary" @click="changePoster"
                   style="margin-top: 10px;">更换海报
        </el-button>
        <br>
        <el-button link type="primary" style="margin-top: 10px;"
                   @click="editTags">
          编辑标签
        </el-button>
      </el-col>
      <el-col :span="8">
       <div style="overflow: hidden">
         <h4 style="float: left;margin: 0">剧情简介</h4>
         <el-button style="float: right"
                    @click="goBack"
                    type="primary">返回
         </el-button>
       </div>
        <p>{{ tableData.synopsis }}</p>
        <el-button link style="position: fixed;top:335px;"
                   @click="editSynopsis"
                   type="primary">修改剧情简介
        </el-button>
      </el-col>
    </el-row>

    <el-row :gutter="10">
      <el-col :span="14">
        <el-tabs v-model="activeName">
          <el-tab-pane label="电影视频" name="first">
            <h4 style="margin-top: 0;">电影视频</h4>
            <div v-if="!tableData.filmUrl">
              <el-result
                  icon="error"
                  title="暂无影片"
                  sub-title="属于预告电影，没有相关影片"
              >
                <template #extra>
                  <el-button type="primary" @click="uploadFilm">添加影片</el-button>
                </template>
              </el-result>
            </div>
            <div style="width:90%;" v-else>
              <video controls preload
                     :src="BASE_URL + tableData.filmUrl"
                     style="width: 100%;height: 100%;">
              </video>
            </div>
          </el-tab-pane>
          <el-tab-pane label="导演信息" name="second">
            <el-row :gutter="10">
              <el-col :span="4">
                <h4 style="margin-top: 0;">导演</h4>
                <div style="text-align: center;">
                  <el-image :src="BASE_URL + tableData.directorPoster"
                            style="width: 120px;height: auto;"
                            alt="Film poster"/>
                  <p>{{ tableData.directorName }} {{ nationalityFormatter(tableData, null, tableData.nationality) }}</p>

                </div>
              </el-col>
              <el-col :span="20">
                <div style="margin-top: 40px;margin-left: 30px;width: 500px">
                  <p style="line-height: 1.5;text-indent: 2em;">{{ tableData.directorIntro }}</p>
                </div>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="演员信息" name="third">
            <div style="overflow: hidden">
              <p style="margin-top: 0;font-size: 16px;font-weight: bold;float: left">
                演员列表 (共{{ actorData.length }}位演员)</p>
              <el-button link type="primary"
                         @click="editFilmActor"
                         style="float: right">编辑电影演员
              </el-button>
            </div>
            <div style="margin-top: 20px;height: 400px">
              <el-scrollbar height="380px">
                <el-row :gutter="10">
                  <el-col :span="6" v-for="item in actorData">
                    <div style="text-align: center;">
                      <el-image :src="BASE_URL + item.poster"
                                style="width: 120px;height: auto;margin: 0 auto;"
                                alt="Film poster"/>
                      <p>{{ item.actorName }} </p>
                      <p style="font-size: 12px;color: #666666">{{ item.participation }}:{{ item.role }}</p>
                    </div>
                  </el-col>
                </el-row>
              </el-scrollbar>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
      <el-col :span="2"></el-col>
      <el-col :span="8">
        <div style="overflow: hidden">
          <h4 style="float: left">预告片</h4>
          <el-button link type="primary"
                     @click="editFilmPreview"
                     style="float: right;line-height: 66px">编辑电影预告片
          </el-button>
        </div>
        <el-scrollbar height="500px">
          <el-row :gutter="10">
            <el-col :span="24" style="margin-top: 10px;"
                    v-for="item in previewData">
              <el-row :gutter="10">
                <el-col :span="14">
                  <el-image :src="BASE_URL + item.thumbnail"
                            style="width: 200px;height: 115px;"
                            @click="lookPreview(item.id)"
                            alt="Film poster"/>
                  <el-dialog style="width: 760px;height:auto;padding: 30px"
                             :before-close="handleLookupClose"
                             v-model="videoUrlDialogVisible">
                    <video :src="BASE_URL + lookupPreviewUrl.videoUrl"
                           controls style="width:700px;height:auto;"/>
                  </el-dialog>
                </el-col>
                <el-col :span="10">
                  <div style="	overflow: hidden;text-overflow: ellipsis;	display: -webkit-box;
	                              	-webkit-line-clamp: 1;	-webkit-box-orient: vertical;"
                       :title=" item.title">
                    <p style="font-weight: bold;line-height: 115px;margin: 0;">{{ item.title }}</p>
                  </div>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </el-scrollbar>
      </el-col>
    </el-row>

  </el-card>


  <el-dialog v-model="tagVisible" title="编辑标签"
             :before-close="handleClose"
             style="width:500px; padding:40px;height: 300px;margin-top: 200px">

    <el-row :gutter="10">
      <el-col :span="22">
        <el-table :data="tagData" width="100%">
          <el-table-column type="index" label="编号" width="80" align="center"/>
          <el-table-column prop="tag" label="标签" align="center"
                           :formatter="tagDataFormatter">
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button link type="primary"
                         @click="tagEdit(scope.row.id, scope.row.tag)">
                修改
              </el-button>
              <el-button link type="danger"
                         @click="deleteTag(scope.row.id)">
                <el-icon size="16">
                  <Delete/>
                </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
      <el-col :span="2">
        <el-button link type="primary" @click="addTag" v-if="tagData.length < 4">
          <el-icon size="16">
            <CirclePlus/>
          </el-icon>
        </el-button>
      </el-col>
    </el-row>

  </el-dialog>

  <el-dialog
      v-model="tagEditVisible"
      :before-close="tagHandleClose"
      style="width:500px; padding:40px;height: auto;margin-top: 260px">
    <el-row :gutter="10">
      <el-col :span="18">
        <el-form>
          <el-form-item label="标签名称">
            <el-select v-model="saveTag.tag" placeholder="请选择标签">
              <el-option
                  v-for="item in tagList"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="saveTagEdit">保存</el-button>
      </el-col>
    </el-row>
  </el-dialog>

  <el-dialog
      v-model="tagSaveVisible"
      :before-close="tagHandleClose"
      style="width:500px; padding:40px;height: auto;margin-top: 260px">
    <el-row :gutter="10">
      <el-col :span="18">
        <el-form>
          <el-form-item label="标签名称">
            <el-select v-model="saveTag.tag" placeholder="请选择标签">
              <el-option
                  v-for="item in tagList"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="6">
        <el-button type="primary" @click="saveTagButton">保存</el-button>
      </el-col>
    </el-row>
  </el-dialog>

  <el-dialog v-model="editFilmInfoVisible"
             title="编辑电影信息"
             :before-close="cancelEditFilmInfo"
             style="width:600px; padding:40px;height: auto;">
    <el-form label-width="100">
      <el-form-item label="电影名称">
        <el-input v-model="tableData.filmName"
                  placeholder="请输入电影名称"></el-input>
      </el-form-item>
      <el-form-item label="英文名称">
        <el-input v-model="tableData.englishName"
                  placeholder="请输入电影英文名称"></el-input>
      </el-form-item>
      <el-form-item label="导演">
        <el-select v-model="tableData.directorId"
                   placeholder="请选择导演"
                   filterable
                   clearable>
          <el-option
              v-for="item in directorData"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="上映地区">
        <el-select v-model="tableData.nationality"
                   placeholder="请选择上映地区"
                   filterable
                   clearable>
          <el-option
              v-for="item in nationalityList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="电影时长">
        <el-input v-model="tableData.duration"
                  placeholder="请输入电影时长"></el-input>
      </el-form-item>
      <el-form-item label="上映时间">
        <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="tableData.releaseDate"
            style="width: 100%;"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="success" @click="saveEditFilmInfo">保存</el-button>
      <el-button type="primary" @click="cancelEditFilmInfo">取消</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="changePosterVisible"
             title="更换电影海报"
             style="width:800px; padding:40px;height: 360px;position: relative;">
    <el-row :gutter="10">
      <el-col :span="8">
        <el-image :src="BASE_URL + tableData.poster"
                  style="width: 180px;height: auto;"
                  alt="Film poster"/>
      </el-col>
      <el-col :span="16">
        <el-form>
          <el-form-item label="电影海报">
            <el-upload
                v-model:file-list="posterFileList"
                v-model:action="actionUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon>
                <Picture/>
              </el-icon>
            </el-upload>
            <el-dialog style="width: 460px; padding: 30px"
                       v-model="posterVisible">
              <img :src="poster"
                   style="width: 400px;"
                   :alt="poster"/>
            </el-dialog>
          </el-form-item>
        </el-form>
        <div style="position: absolute; right: 20px; bottom: 0;">
          <el-button type="success" @click="savePoster">保存</el-button>
          <el-button type="primary" @click="cancelPoster">取消</el-button>
        </div>
      </el-col>
    </el-row>
  </el-dialog>

  <el-dialog v-model="editSynopsisVisible"
             title="编辑电影简介"
             :before-close="cancelEditSynopsis"
             style="width:600px; padding:40px;height: auto;">
    <el-form>
      <el-form-item label="电影简介">
        <el-input
            v-model="tableData.synopsis"
            :autosize="{ minRows: 6, maxRows: 4 }"
            maxlength="200"
            show-word-limit
            type="textarea"
            placeholder="请输入相关信息"
            style="width: 91%;"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="success" @click="saveEditSynopsis">保存</el-button>
      <el-button type="primary" @click="cancelEditSynopsis">取消</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="editFilmActorVisible"
             title="编辑演员信息"
             :before-close="cancelEditActor"
             style="width:1000px; padding:40px;height: 500px;">
    <el-scrollbar height="320">
      <div style="height: 320px;width: 98%;text-align: center;">
        <el-row :gutter="10">
          <el-col :span="6" v-for="item in actorData">
            <el-card style="margin-top: 5px; border-radius: 10px;height: 240px;">
              <el-avatar style="width: 100px; height: 100px">
                <el-image :src="BASE_URL + item.poster" alt="Actor poster"
                          style="height: 100px"/>
              </el-avatar>
              <p style="font-size: 16px">{{ item.actorName }}</p>
              <p style="font-size: 14px;">{{ item.participation }} {{ item.role }}</p>
              <el-button type="primary" size="small"
                         @click="editHaveFilmActor(item.id)">编辑
              </el-button>
              <el-button type="danger" size="small"
                         @click="deleteFilmActor(item.id)">删除
              </el-button>

            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-scrollbar>
    <template #footer>
      <el-button type="success" @click="addActor">添加</el-button>
      <el-button type="primary" @click="cancelEditActor">完成</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="actorVisible"
             :title="actorTitle"
             width="40%"
             :before-close="handleCloseFilmActor"
             style="padding: 40px;margin-top: 200px;">
    <el-form ref="form" label-width="100px">
      <el-form-item label="演员姓名">
        <el-select
            v-model="saveFilmActorParam.actorId"
            clearable
            filterable
            style="width:330px;"
            placeholder="请输入演员姓名">
          <el-option
              v-for="item in allActorData"
              :key="item.value"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色">
        <el-select v-model="saveFilmActorParam.participation"
                   style="width:100px;"
                   placeholder="请选择参与方式">
          <el-option label="饰演" value="饰演"/>
          <el-option label="配音" value="配音"/>
        </el-select>
        <el-input v-model="saveFilmActorParam.role" style="width:220px;margin-left: 10px"
                  placeholder="请输入演员角色"/>
      </el-form-item>
      <el-form-item label="排序">
        <el-input v-model="saveFilmActorParam.sort" style="width:330px;"
                  placeholder="请输入排序序号"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="danger" @click="handleCloseFilmActor">取消</el-button>
      <el-button type="primary" @click="saveFilmActor">保存</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="editFilmPreviewVisible"
             title="编辑电影预告片"
             :before-close="cancelEditFilmPreview"
             style="width:1000px; padding:40px;height: auto;">
    <el-table :data="previewData"
              style="margin-top: 20px;width: 100%;height: 400px">
      <el-table-column type="index" label="序号" width="80" align="center"/>
      <el-table-column prop="title" label="预告片标题" align="center"/>
      <el-table-column label="预告片图片" align="center">
        <template #default="scope">
          <el-image :src="BASE_URL + scope.row.thumbnail"
                    :alt="thumbnail"
                    style="width:150px;height:auto;"/>
        </template>
      </el-table-column>
      <el-table-column label="预告片" align="center">
        <template #default="scope">
          <video :src="BASE_URL + scope.row.videoUrl"
                 controls style="width:150px;height:auto;"/>
        </template>
      </el-table-column>
      <el-table-column label="预告片时长" align="center">
        <template #default="scope">
          {{ scope.row.minute }} : {{ scope.row.second }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button type="primary" link @click="editPreview(scope.row.id)">编辑</el-button>
          <el-button type="danger" link @click="deletePreview(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button type="success" @click="addPreview">添加</el-button>
      <el-button type="primary" @click="cancelEditFilmPreview">完成</el-button>
    </template>
  </el-dialog>

  <el-dialog v-model="previewVisible"
             :title="previewTitle"
             style="width: 1000px;padding: 40px;height: 380px;"
             :before-close="cancelPreview">
    <el-form label-width="100px">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="预告片标题">
            <el-input v-model="savePreviewParam.title"
                      style="width: 90%;" placeholder="请输入预告片标题"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预告片时长">
            <el-input id="time" type="text"
                      style="width: 30%;"
                      v-model="savePreviewParam.minute"
                      placeholder="(分)"/>
            <span style="margin: 0 5px;font-size: 22px;font-weight: bold">:</span>
            <el-input id="time" type="text"
                      style="width: 30%;"
                      v-model="savePreviewParam.second"
                      placeholder="(秒)"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="预告片缩略图">
            <el-upload
                v-model:file-list="thumbnailFileList"
                v-model:action="actionThumbnailUrl"
                name="file"
                limit="1"
                list-type="picture-card"
                :on-preview="handleThumbnailCardPreview"
                :on-remove="handleThumbnailRemove">
              <el-icon>
                <Picture/>
              </el-icon>
            </el-upload>
            <el-dialog v-model="thumbnailVisible">
              <img :src="thumbnail" style="width: 400px;" :alt="thumbnail"/>
            </el-dialog>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="预告片视频">
            <el-upload
                v-model:file-list="previewFileList"
                v-model:action="previewUrl"
                multiple
                list-type="text"
                :on-remove="removePreview"
                :limit="1">
              <el-button style="width: 150px;" type="primary">上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">上传视频文件，支持格式：mp4，文件大小不超过1GB</div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="danger"
               style="float: right;margin-right: 15px"
               @click="cancelPreview">取消
    </el-button>
    <el-button type="primary"
               style="float: right;margin-right: 15px"
               @click="savePreview">保存
    </el-button>
  </el-dialog>

  <el-dialog v-model="uploadFilmVisible"
             style="width: 600px; padding: 30px;height: 340px;position: relative"
             title="添加电影">
    <el-form>
      <el-form-item label="电影视频"
                    style="margin-top: 40px">
        <el-upload
            v-model:file-list="filmFileList"
            class="upload-demo"
            v-model:action="saveFilmUrl"
            multiple
            :on-remove="removeFilm"
            :on-change="handleVideoChange"
            :on-preview="handleVideoPreview"
            :limit="1"
        >
          <el-button style="width: 150px;"
                     type="primary">上传视频
          </el-button>
          <template #tip>
            <div class="el-upload__tip">
              上传视频文件，支持格式：mp4，文件大小不超过3GB
            </div>
          </template>
        </el-upload>
      </el-form-item>
      <el-dialog style="width: 600px; padding: 30px" v-model="filmVisible">
        <video :src="videoUrl"
               style="width: 540px;"
               controls/>
      </el-dialog>
    </el-form>
    <template #footer>
      <el-button type="primary"
                 style="position: absolute;right: 30px;bottom: 30px"
                 @click="saveFilm">保存
      </el-button>
      <el-button @click="cancel"
                 style="position: absolute;right: 100px;bottom: 30px"
      >取消
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import axios from "axios";
import qs from "qs";
import {ElMessage, ElMessageBox} from "element-plus";
import {onMounted, ref} from "vue";
import router from "@/router";

const activeName = ref('first')
const tagList = ref([]);
const nationalityList = ref([]);
onMounted(() => {
  loadDictOptions(tagList, 'tag');
  loadDictOptions(nationalityList, 'nationality');
});
const nationalityFormatter = (row, column, cellValue, index) => {
  if (!nationalityList.value) {
    return cellValue;
  }
  for (let item of nationalityList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
const tagFormatter = (row, column, cellValue, index) => {
  if (!tagList.value || !cellValue) {
    return cellValue;
  }
  // 将斜杠分隔的字符串转换为数组
  const tagsArray = cellValue.split('/');
  // 查找并替换每个标签值
  const formattedTags = tagsArray.map(tagValue => {
    for (let item of tagList.value) {
      if (item.value === tagValue) {
        return item.label; // 返回对应的汉字内容
      }
    }
    return tagValue; // 如果没有找到对应的汉字内容，则保留原始值
  });
  // 将格式化后的标签数组重新组合为字符串
  return formattedTags.join('  ');
};
const tagDataFormatter = (row, column, cellValue, index) => {
  if (!tagList.value) {
    return cellValue;
  }
  for (let item of tagList.value) {
    if (item.value === cellValue) {
      cellValue = item.label;
    }
  }
  return cellValue;
}
let filmId = new URLSearchParams(window.location.search).get('id');
const tableData = ref([]);
const search = () => {
  axios.get(BASE_URL + '/v1/film/select?id=' + filmId)
      .then((response) => {
        if (response.data.code === 2000) {
          tableData.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  search();
});


/** 标签开始*/

const tagVisible = ref(false);
const tagData = ref([]);

const saveTag = ref({
  tag: ''
});

const editTags = () => {
  tagVisible.value = true;
  axios.get(BASE_URL + '/v1/tag/select/' + filmId)
      .then((response) => {
        if (response.data.code === 2000) {
          tagData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
const refreshTag = () => {
  axios.get(BASE_URL + '/v1/tag/select/' + filmId)
      .then((response) => {
        if (response.data.code === 2000) {
          tagData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
const handleClose = () => {
  tagVisible.value = false;
  search()
}
const tagEditVisible = ref(false);
const tagId = ref();
const tagEdit = (id, tag) => {
  tagEditVisible.value = true;
  tagId.value = id;
  saveTag.value.tag = tag;
}
const saveTagEdit = () => {
  ElMessageBox.confirm('您确定要修改吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    saveTag.value.id = tagId;
    let data = qs.stringify(saveTag.value);
    axios.put(BASE_URL + '/v1/tag/update', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('修改成功!')
            tagEditVisible.value = false;
            refreshTag()
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        });
  }).catch(() => {
    ElMessageBox.close();
  });
}
const tagHandleClose = () => {
  ElMessageBox.confirm('您确定要取消保存吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    tagEditVisible.value = false;
    tagSaveVisible.value = false;
    saveTag.value = {}
  }).catch(() => {
  });
}
const deleteTag = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/tag/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!')
            refreshTag()
            search(id)
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });
}
const tagSaveVisible = ref(false);
const addTag = () => {
  tagSaveVisible.value = true;
}
const saveTagButton = () => {
  ElMessageBox.confirm('您确定要保存吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    saveTag.value.id = tagId;
    saveTag.value.filmId = filmId;
    let data = qs.stringify(saveTag.value);
    axios.post(BASE_URL + '/v1/tag/save', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('修改成功!')
            tagSaveVisible.value = false;
            refreshTag()
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        });
  }).catch(() => {
    ElMessageBox.close();
  });
}

/**标签结束 */

const goBack = () => {
  router.back(-1)
}

const actorData = ref([]);
const searchActor = () => {
  axios.get(BASE_URL + '/v1/filmActor/select/' + filmId)
      .then((response) => {
        if (response.data.code === 2000) {
          actorData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  searchActor();
})
const directorData = ref([]);
const searchDirector = () => {
  axios.get(BASE_URL + '/v1/director/select?')
      .then((response) => {
        if (response.data.code === 2000) {
          directorData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
onMounted(() => {
  searchDirector();
})

const editFilmInfoVisible = ref(false);
const editFilmInfo = () => {
  editFilmInfoVisible.value = true;
}
const saveEditFilmInfo = () => {
  ElMessageBox.confirm('您确定要修改吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    let data = qs.stringify(tableData.value);
    axios.put(BASE_URL + '/v1/film/update', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('修改成功!')
            editFilmInfoVisible.value = false;
            search()
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        });
  }).catch(() => {
    ElMessageBox.close();
  });
}
const cancelEditFilmInfo = () => {
  editFilmInfoVisible.value = false;
  search()
}
const changePosterVisible = ref(false);
const changePoster = () => {
  changePosterVisible.value = true;
}
/**图片上传相关代码开始**/
const posterFileList = ref([]);
const poster = ref('');
const posterVisible = ref(false);
const actionUrl = ref(BASE_URL + '/v1/filmPoster/upload');
const handleRemove = (uploadFile, uploadFiles) => {
  let posterUrl = uploadFile.response.data;
  axios.post(BASE_URL + '/v1/filmPoster/remove?posterUrl=' + posterUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
        }
      })
}
const handlePictureCardPreview = (uploadFile) => {
  poster.value = uploadFile.url
  posterVisible.value = true;
}
/**图片上传相关代码结束**/

const savePoster = () => {
  ElMessageBox.confirm('您确定要修改吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    let data = qs.stringify({
      id: filmId,
      poster: posterFileList.value[0].response.data,
    });
    axios.put(BASE_URL + '/v1/film/update', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('修改成功!')
            changePosterVisible.value = false;
            search()
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        })
  }).catch(() => {
    ElMessageBox.close();
  });
}
const cancelPoster = () => {
  changePosterVisible.value = false;
  posterFileList.value = [];
  search()
}
const editSynopsisVisible = ref(false);
const editSynopsis = () => {
  editSynopsisVisible.value = true;
}
const saveEditSynopsis = () => {
  ElMessageBox.confirm('您确定要修改吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    let data = qs.stringify({
      id: filmId,
      synopsis: tableData.value.synopsis,
    });
    axios.put(BASE_URL + '/v1/film/update', data)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('修改成功!')
            editSynopsisVisible.value = false;
            search(id)
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        })
  }).catch(() => {
    ElMessageBox.close();
  })
}
const cancelEditSynopsis = () => {
  editSynopsisVisible.value = false;
  search()
}
const editFilmActorVisible = ref(false);
const editFilmActor = () => {
  editFilmActorVisible.value = true;
}
const cancelEditActor = () => {
  editFilmActorVisible.value = false;
  searchActor();
}
const actorVisible = ref(false);
const addActor = () => {
  actorTitle.value = '添加电影演员信息';
  actorVisible.value = true;
}
const actorTitle = ref('添加电影演员信息');
const saveFilmActorParam = ref({
  filmId: filmId,
  actorId: '',
  participation: '',
  role: '',
  sort: ''
})
const saveFilmActor = () => {
  if (saveFilmActorParam.value.actorId === null || saveFilmActorParam.value.actorId === '') {
    errorInfo('请选择演员');
    return;
  }
  if (saveFilmActorParam.value.participation === null || saveFilmActorParam.value.participation === '') {
    errorInfo('请选择角色');
    return;
  }
  if (saveFilmActorParam.value.role === null || saveFilmActorParam.value.role === '') {
    errorInfo('请输入饰演角色');
    return;
  }
  let data = qs.stringify(saveFilmActorParam.value);
  axios.post(BASE_URL + '/v1/filmActor/save', data).then((response) => {
    if (response.data.code === 2000) {
      OKInfo('保存成功!');
      actorVisible.value = false;
      saveFilmActorParam.value = {
        filmId: filmId,
        actorId: '',
        participation: '',
        role: '',
        sort: ''
      };
      searchActor();
    } else {
      ElMessage({
        message: response.data.msg,
        type: 'error',
        showClose: true,
        center: true,
      })
    }
  })
};
const handleCloseFilmActor = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    saveFilmActorParam.value = {
      filmId: filmId,
      actorId: '',
      participation: '',
      role: '',
      sort: ''
    };
    actorVisible.value = false;
  }).catch(() => {
    //取消没有操作
  });
}
const editHaveFilmActor = (id) => {
  actorVisible.value = true;
  actorTitle.value = '编辑电影演员信息';
  axios.get(BASE_URL + '/v1/filmActor/select/selectById/' + id)
      .then((response) => {
        if (response.data.code === 2000) {
          saveFilmActorParam.value = response.data.data[0];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}

const deleteFilmActor = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/filmActor/delete/' + id)
        .then((response) => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!');
            searchActor()
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        });
  }).catch(() => {
    //取消没有操作
  })
}
const allActorData = ref([]);
const searchAllActor = () => {
  axios.get(BASE_URL + '/v1/actor/select?')
      .then((response) => {
        if (response.data.code === 2000) {
          allActorData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      })
}
onMounted(() => {
  searchAllActor()
})
const previewData = ref([]);
const selectPreview = () => {
  axios.get(BASE_URL + '/v1/preview/selectByFilmId/' + filmId)
      .then(response => {
        if (response.data.code === 2000) {
          previewData.value = response.data.data;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
};
// 测试添加
onMounted(() => {
  selectPreview();
})
const editFilmPreviewVisible = ref(false);
const editFilmPreview = () => {
  editFilmPreviewVisible.value = true;
}
const cancelEditFilmPreview = () => {
  editFilmPreviewVisible.value = false;
  search()
}
const savePreviewParam = ref({
  filmId: filmId,
  title: '',
  minute: '',
  second: '',
  thumbnail: '',
  videoUrl: ''
});


const previewVisible = ref(false);
const previewTitle = ref('添加预告片');

const thumbnailFileList = ref([]);
const thumbnail = ref('');
const thumbnailVisible = ref(false);
const actionThumbnailUrl = ref(BASE_URL + '/v1/thumbnail/upload');
const handleThumbnailRemove = (uploadFile, uploadFiles) => {
  let thumbnailUrl = uploadFile.response?.data;
  if (thumbnailUrl) {
    axios.post(BASE_URL + '/v1/thumbnail/remove?thumbnailUrl=' + thumbnailUrl)
        .then(response => response.data.code === 2000 && ElMessage.success('删除成功!'));
  }
};

const handleThumbnailCardPreview = (uploadFile) => {
  thumbnail.value = uploadFile.url;
  thumbnailVisible.value = true;
};


const previewFileList = ref([]);
const previewUrl = ref(BASE_URL + '/v1/preview/upload');
const removePreview = (uploadFile, uploadFiles) => {
  let previewUrl = uploadFile.response?.data;
  if (previewUrl) {
    axios.post(BASE_URL + '/v1/preview/remove?previewUrl=' + previewUrl)
        .then(response => response.data.code === 2000 && ElMessage.success('删除成功!'));
  }
};

const addPreview = () => {
  previewTitle.value = '添加预告片';
  previewVisible.value = true;
};

const savePreview = () => {
  if (savePreviewParam.value.title === null || savePreviewParam.value.title === '') {
    errorInfo('预告片标题不能为空');
    return;
  }
  if (savePreviewParam.value.minute === '' || savePreviewParam.value.minute === null) {
    errorInfo('预告片时长不能为空');
    return;
  }
  if (savePreviewParam.value.second === '' || savePreviewParam.value.second === null) {
    errorInfo('预告片时长不能为空');
    return;
  }
  if (savePreviewParam.value.minute < 0 || savePreviewParam.value.minute > 59) {
    errorInfo('预告片时长不合法');
    return;
  }
  if (thumbnailFileList.value.length === 0) {
    errorInfo('预告片缩略图不能为空');
    return;
  }
  if (previewFileList.value.length === 0) {
    errorInfo('预告片视频不能为空');
    return;
  }
  savePreviewParam.value.filmId = filmId;
  savePreviewParam.value.thumbnail = thumbnailFileList.value[0].response.data;
  savePreviewParam.value.videoUrl = previewFileList.value[0].response.data;
  let data = qs.stringify(savePreviewParam.value);
  axios.post(BASE_URL + '/v1/preview/save', data)
      .then(response => {
        if (response.data.code === 2000) {
          OKInfo('保存成功!');
          selectPreview()
          previewVisible.value = false;
          savePreviewParam.value = {};
          thumbnailFileList.value = [];
          previewFileList.value = [];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });

};

const cancelPreview = () => {
  ElMessageBox.confirm('您确定要取消吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    Info('已取消保存');
    previewVisible.value = false;
    savePreviewParam.value = {
      title: '',
      minute: '',
      second: '',
      thumbnail: '',
      videoUrl: ''
    };
    thumbnailFileList.value = [];
    previewFileList.value = [];
  }).catch(() => {
    //取消没有操作
  });
};


const editPreview = (id) => {
  previewVisible.value = true;
  previewTitle.value = '编辑信息';
  axios.get(BASE_URL + '/v1/preview/selectById/' + id)
      .then(response => {
        if (response.data.code === 2000) {
          savePreviewParam.value = response.data.data[0];
          previewFileList.value = [{
            url: BASE_URL + savePreviewParam.value.videoUrl,
            response: {data: savePreviewParam.value.videoUrl}
          }];
          thumbnailFileList.value = [{
            url: BASE_URL + savePreviewParam.value.thumbnail,
            response: {data: savePreviewParam.value.thumbnail}
          }];
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
};

const deletePreview = (id) => {
  ElMessageBox.confirm('您确定要删除吗', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    axios.delete(BASE_URL + '/v1/preview/delete/' + id)
        .then(response => {
          if (response.data.code === 2000) {
            OKInfo('删除成功!');
            selectPreview();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        })
  }).catch(() => {
    Info('已取消删除')
  });
}
const videoUrlDialogVisible = ref(false);
const lookupPreviewUrl = ref([])
const lookPreview = (id) => {
  axios.get(BASE_URL + '/v1/preview/selectById/' + id)
      .then(response => {
        if (response.data.code === 2000) {
          lookupPreviewUrl.value = response.data.data[0];
          videoUrlDialogVisible.value = true;
        } else {
          ElMessage({
            message: response.data.msg,
            type: 'error',
            showClose: true,
            center: true,
          });
        }
      });
}
const handleLookupClose = () => {
  videoUrlDialogVisible.value = false;
}

const uploadFilm = () => {
  uploadFilmVisible.value = true;
}
const uploadFilmVisible = ref(false);
/**视频上传相关代码开始**/
const filmFileList = ref([]);
const isShow = ref(false);
const saveFilmUrl = ref(BASE_URL + '/v1/filmUrl/upload');
const removeFilm = (uploadFile, uploadFiles) => {
  let filmUrl = uploadFile.response.data;
  axios.post(BASE_URL + '/v1/filmUrl/remove?filmUrl=' + filmUrl)
      .then((response) => {
        if (response.data.code === 2000) {
          ElMessage.success('删除成功!');
          isShow.value = false;
        }
      })
}
const videoUrl = ref('');
const handleVideoChange = (uploadFile) => {
  const file = uploadFile.raw;
  if (!file) return;
  videoUrl.value = URL.createObjectURL(file);
}
const filmVisible = ref(false);
const handleVideoPreview = (uploadFile) => {
  filmVisible.value = true;
}

/**视频上传相关代码结束**/

const saveFilm = () => {
  ElMessageBox.confirm('确定上传该视频吗？', '提示', {
    customClass: 'custom-message-box',
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    draggable: true,
  }).then(() => {
    let data = qs.stringify({
      id: filmId,
      releaseStatus: 1,
      filmUrl: filmFileList.value[0].response.data,
    });
    axios.put(BASE_URL + '/v1/film/update', data)
        .then((response) => {
          if (response.data.code === 2000) {
            ElMessage.success('上传成功!');
            uploadFilmVisible.value = false;
            filmFileList.value = [];
            search();
          } else {
            ElMessage({
              message: response.data.msg,
              type: 'error',
              showClose: true,
              center: true,
            });
          }
        });
  }).catch(() => {

  })
}
const cancel = () => {
  Info('已取消上传');
  uploadFilmVisible.value = false;
  filmFileList.value = [];
}

</script>

<style scoped>
p {
  margin: 10px 0;
}
</style>